import api from '@/api'
import { deepCopy, setPage } from '@/utils/util'

const initPage = {
    size: 10,
    number: 0,
    total: 0,
    pages: 0,
    filter: {
        enabled: null
    }
}

// state
const state = {
    data: {
        documents: [],
        classDucument: []
    },

    ui: {
        page: deepCopy(initPage)
    }
}

// getters
const getters = {
    documents: state => state.data.documents,
    classDucument: state => state.data.classDucument,

    documentsTotal: state => state.ui.page.total
}

// actions
const actions = {

    getDocuments({ state, commit }, params = {}, loading) {
        api.getDocuments({
            loading: params.loading === false ? false : true,
            method: 'post',
            data: JSON.stringify(params) != "{}" ? params : state.ui.page,
            success: (res) => {
                const { pages, total } = res
                commit('SETDOCUMENTPAGE', { pages, total })

                let documents = res.content
                commit('SETDOCUMENTS', { documents })
            }
        })
    },

    removeDocument({ dispatch }, params) {
        api.removeDocument({
            loading: true,
            method: 'post',
            data: params,
            success: (res) => {
                dispatch('getDocuments')
            }
        })
    },

    addDocument({ dispatch }, params) {
        api.addDocument({
            method: 'put',
            data: params,
            success: (res) => {
                dispatch('getDocuments')
            }
        })
    },

    editDocument({ dispatch }, params) {
        api.editDocument({
            method: 'put',
            data: params,
            success: (res) => {
                dispatch('getDocuments')
            }
        })
    },

    getClassDocument({ commit }, params) {
        api.getClassDocument({
            method: 'get',
            data: params,
            success: (res) => {
                let classDucument = res
                commit('SETCLASSDOCUMENT', { classDucument })
            }
        })
    }

}

// mutations
const mutations = {

    SETDOCUMENTS(state, payload) {
        state.data.documents = payload.documents
    },

    SETCLASSDOCUMENT(state, payload) {
        state.data.classDucument = payload.classDucument
    },

    SETDOCUMENTPAGE(state, page) {
        page && setPage(state.ui.page, page)
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}